﻿import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:azring/common/res/gaps.dart';
import 'package:azring/common/utils/change_notifier_manage.dart';
import 'package:azring/common/utils/keyboard_util.dart';
import 'package:azring/widget/my_scroll_view.dart';
import 'package:azring/core/controllers/auth_controller.dart';

/// 设置密码页面
class SetPasswordView extends StatefulWidget {
  const SetPasswordView({super.key});

  @override
  _SetPasswordViewState createState() => _SetPasswordViewState();
}

class _SetPasswordViewState extends State<SetPasswordView>
    with ChangeNotifierMixin<SetPasswordView> {
  final TextEditingController _passwordLogic = TextEditingController();
  final TextEditingController _confirmPasswordLogic = TextEditingController();
  final FocusNode _passwordFocus = FocusNode();
  final FocusNode _confirmPasswordFocus = FocusNode();
  bool _clickable = false;
  bool _isPasswordFocused = false;
  bool _isConfirmPasswordFocused = false;

  // 密码可见性
  bool _obscurePassword = true;
  bool _obscureConfirmPassword = true;

  // 注册参数
  String? _username;
  String? _code;
  String? _uuid;

  @override
  Map<ChangeNotifier, List<VoidCallback>?>? changeNotifier() {
    final List<VoidCallback> callbacks = <VoidCallback>[_verify];
    return <ChangeNotifier, List<VoidCallback>?>{
      _passwordLogic: callbacks,
      _confirmPasswordLogic: callbacks,
      _passwordFocus: null,
      _confirmPasswordFocus: null,
    };
  }

  @override
  void initState() {
    super.initState();
    // 接收注册参数
    final arguments = Get.arguments as Map<String, dynamic>?;
    if (arguments != null) {
      _username = arguments['username'];
      _code = arguments['code'];
      _uuid = arguments['uuid'];
    }

    // 添加焦点监听器
    _passwordFocus.addListener(_onPasswordFocusChange);
    _confirmPasswordFocus.addListener(_onConfirmPasswordFocusChange);
  }

  void _onPasswordFocusChange() {
    if (mounted) {
      setState(() {
        _isPasswordFocused = _passwordFocus.hasFocus;
      });
    }
  }

  void _onConfirmPasswordFocusChange() {
    if (mounted) {
      setState(() {
        _isConfirmPasswordFocused = _confirmPasswordFocus.hasFocus;
      });
    }
  }

  @override
  void dispose() {
    _passwordFocus.removeListener(_onPasswordFocusChange);
    _confirmPasswordFocus.removeListener(_onConfirmPasswordFocusChange);
    super.dispose();
  }

  void _verify() {
    final String password = _passwordLogic.text;
    final String confirmPassword = _confirmPasswordLogic.text;
    bool clickable = true;
    if (password.isEmpty || password.length < 8) {
      clickable = false;
    }
    if (confirmPassword.isEmpty || confirmPassword != password) {
      clickable = false;
    }
    if (clickable != _clickable) {
      setState(() {
        _clickable = clickable;
      });
    }
  }

  void _confirm() async {
    if (_username == null || _code == null || _uuid == null) {
      Toast.show('注册信息不完整，请重新注册');
      Get.back();
      return;
    }

    // 确保AuthLogic已初始化
    if (!Get.isRegistered<AuthController>()) {
      Get.put<AuthController>(AuthController(), permanent: true);
    }

    // 调用注册接口
    await AuthController.to.register(
      username: _username!,
      password: _passwordLogic.text,
      code: _code!,
      uuid: _uuid!,
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: MyScrollView(
          keyboardConfig: KeyboardUtil.getKeyboardActionsConfig(
              context, <FocusNode>[_passwordFocus, _confirmPasswordFocus]),
          padding: const EdgeInsets.all(24),
          children: _buildBody(),
        ),
      ),
    );
  }

  List<Widget> _buildBody() {
    return <Widget>[
      Gaps.vGap16,
      // 标题
      _buildTitle(),
      Gaps.vGap32,
      // 密码输入框
      _buildPasswordInput(),
      Gaps.vGap8,
      // 密码要求提示
      _buildPasswordHint(),
      Gaps.vGap18,
      // 确认密码输入框
      _buildConfirmPasswordInput(),
      SizedBox(height: 199.h),
      // 确认按钮
      _buildConfirmButton(),
    ];
  }

  // 构建标题
  Widget _buildTitle() {
    return Container(
      alignment: Alignment.topLeft,
      child: Text(
        "设置密码",
        style: TextStyle(
          color: Colors.white,
          fontSize: 20.sp,
          fontWeight: FontWeight.w500,
        ),
      ),
    );
  }

  // 构建密码输入框
  Widget _buildPasswordInput() {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color:
              _isPasswordFocused ? const Color(0xffF45757) : Colors.transparent,
          width: 0.5.w,
        ),
      ),
      child: TextField(
        focusNode: _passwordFocus,
        controller: _passwordLogic,
        style: const TextStyle(color: Colors.white, fontSize: 14),
        obscureText: _obscurePassword,
        textAlignVertical: TextAlignVertical.center,
        onTap: () {
          setState(() {
            // 确保焦点变化时更新UI
          });
        },
        decoration: InputDecoration(
          hintText: "请输入密码",
          hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
          border: InputBorder.none,
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
          suffixIcon: GestureDetector(
            onTap: () {
              setState(() {
                _obscurePassword = !_obscurePassword;
              });
            },
            child: Icon(
              _obscurePassword ? Icons.visibility_off : Icons.visibility,
              color: const Color(0xFF666666),
              size: 20,
            ),
          ),
        ),
      ),
    );
  }

  // 构建密码要求提示
  Widget _buildPasswordHint() {
    return Container(
      alignment: Alignment.centerLeft,
      child: Text(
        "密码为8-20个字符,必须包含数字、大写字母和小写字母,不能包含空格",
        style: TextStyle(
          color: Colors.white.withOpacity(0.6),
          fontSize: 12.sp,
        ),
      ),
    );
  }

  // 构建确认密码输入框
  Widget _buildConfirmPasswordInput() {
    return Container(
      height: 56.h,
      decoration: BoxDecoration(
        color: const Color(0xFF282528),
        borderRadius: BorderRadius.circular(12.r),
        border: Border.all(
          color: _isConfirmPasswordFocused
              ? const Color(0xffF46425)
              : Colors.transparent,
          width: 0.5.w,
        ),
      ),
      child: TextField(
        focusNode: _confirmPasswordFocus,
        controller: _confirmPasswordLogic,
        style: const TextStyle(color: Colors.white, fontSize: 14),
        obscureText: _obscureConfirmPassword,
        textAlignVertical: TextAlignVertical.center,
        onTap: () {
          setState(() {
            // 确保焦点变化时更新UI
          });
        },
        decoration: InputDecoration(
          hintText: "请确认密码",
          hintStyle: const TextStyle(color: Colors.white, fontSize: 14),
          border: InputBorder.none,
          contentPadding:
              const EdgeInsets.symmetric(horizontal: 25, vertical: 18),
          suffixIcon: GestureDetector(
            onTap: () {
              setState(() {
                _obscureConfirmPassword = !_obscureConfirmPassword;
              });
            },
            child: Icon(
              _obscureConfirmPassword ? Icons.visibility_off : Icons.visibility,
              color: const Color(0xFF666666),
              size: 20,
            ),
          ),
        ),
      ),
    );
  }

  // 构建确认按钮
  Widget _buildConfirmButton() {
    return Container(
      width: double.infinity,
      height: 56.h,
      decoration: BoxDecoration(
        color: _clickable
            ? const Color(0xffF46425)
            : const Color(0xffF46425).withOpacity(0.5),
        borderRadius: BorderRadius.circular(999.r),
      ),
      child: Material(
        color: Colors.transparent,
        child: InkWell(
          onTap: _clickable ? _confirm : null,
          borderRadius: BorderRadius.circular(999.r),
          child: Center(
            child: Text(
              "确认",
              style: TextStyle(
                color:
                    _clickable ? Colors.white : Colors.white.withOpacity(0.5),
                fontSize: 16.sp,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ),
      ),
    );
  }
}
